<template>
<div>
   <div class="search">
    <input v-model ="keyWord" class="search-input" type="text" placeholder="请输入城市名或拼音">
  </div>
  <div class="search-conent" ref="searchWrapper" v-show = 'keyWord'>
      <ul>
        <li class="search-item border-bottom"
         v-for="(item,index) in list"
          :key="index"
          @click="handleChangeCity(item.name)"
          >{{item.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">暂无匹配的城市</li>
      </ul>
  </div>
</div>
  
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations} from 'vuex'
export default {
  name:'citySearch',
  components:{},
  props:{
    cities:Object
  },
  data(){
    return {
      keyWord:'',
      timer:null,
      list:[]
    }
  },
  watch:{
    keyWord(){
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.keyWord){
        this.list = []
        return 
      }
      this.timer = setTimeout(() => {
        const resoult  = []
        for (const key in this.cities) {
          this.cities[key].forEach((e) => {
            if(e.spell.indexOf(this.keyWord) > -1 ||
             e.name.indexOf(this.keyWord) > -1 )
             {
               resoult.push(e)
             }
          });
        }
        this.list = resoult
      },100)
      
    }
  },
  computed:{
    hasNoData(){
      return !this.list.length
    }
  },
  methods:{
     handleChangeCity(city){
          // this.$store.commit('changeCity',city)
          this.changeCity(city)
          this.$router.push({path:'/'})
      },
      ...mapMutations(['changeCity'])
  },
  created(){},
  mounted(){
    this.scroll = new Bscroll(this.$refs.searchWrapper)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  height 0.62rem
  padding 0 0.1rem 0.1rem 0.1rem
  background $bgColor
  box-sizing content-box
  .search-input
    color #666
    width 100%
    height 0.62rem
    line-height 0.62rem
    text-align center
.search-conent
  overflow hidden
  background #eee
  z-index 1
  position absolute
  top 1.58rem
  left 0
  right 0
  bottom 0
  .search-item
    line-height .62rem
    padding-left .2rem
    background #fff
    color #666
</style>